<?php


namespace app\backend\modules\content\services;


use app\common\exceptions\BizException;
use app\common\models\Product;
use app\common\models\ProductChannel;
use app\common\models\ProductProperty;
use Illuminate\Support\Facades\DB;

class ProductService
{
    public function getList(array $params):array {
        $query = Product::site()->select();
        if($params['cid']){
            $query->where('cid',$params['cid']);
        }
        if($params['name']){
            $query->where('name','like','%'.$params['name'].'%');
        }
        $min_price = $params['min_price'];
        $max_price = $params['max_price'];
        if($min_price && $max_price){
            $query = $query->where('price','>=',$min_price);
            $query = $query->where('price','<=',$max_price);
        }else if($min_price){
            $query = $query->where('price','>=',$min_price);
        }else if($max_price){
            $query = $query->where('price','<=',$max_price);
        }
        $list = $query
            ->with(['category' => function($query) {
                return $query->select('id','name');
            }])
            ->with('channel')
            ->with('property')
            ->orderBy('id', 'desc')
            ->paginate(10);
        $list->map(function ($v){
            $v->cname = '';
            if($v['category']&&$v['category']['name']){
                $v->cname = $v['category']['name'];
            }
        });
        return $list->toArray();
    }

    public function saveData($channelData,$productData,$productmodel)
    {
        DB::beginTransaction();
        if(!$productmodel->save()){
            DB::rollBack();
            throw new BizException('保存失败');
        }
        $model = new ProductChannel();
        $data = [];
        if ($channelData) {
            foreach ($channelData as $k => $v) {
                $data[$k] = [
                    'id' => $v['id'],
                    'site_id' => $productData['site_id'],
                    'product_id' => $productData['id'],
                    'name' => $v['name'],
                    'url' => $v['url'],
                    'created_at' => time()
                ];
            }
        }
        if ($productData['id']) {
            $oldData = $model::site()->select()
                ->where('product_id',$productData['id'])
                ->get();
            $oldIds = [];
            foreach ($oldData as $k => $v) {
                $oldIds[] = $v['id'];
            }
            $newIds = [];
            $insertData = [];
            $updateData = [];
            foreach ($data as $k => $v) {
                if ($v['id']) {
                    $newIds[] = $v['id'];
                    array_push($updateData,$v);
                }else{
                    array_push($insertData,$v);
                }
            }
            $model->insert($insertData);
            foreach ($updateData as $k => $v) {
                if ($v['id']) {
                    ProductChannel::where('id',$v['id'])->update(['name'=>$v['name'],'url'=>$v['url']]);
                }
            }
            $deleteIds = [];
            foreach ($oldIds as $k => $v) {
                if (!in_array($v,$newIds)) {
                    array_push($deleteIds,$v);
                }
            }
            $model::whereIn('id',$deleteIds)->delete();
        }
        if(!$model){
            DB::rollBack();
            throw new BizException('保存失败');
        }
        DB::commit();
    }

    public function savePropertyData($productData,$propertyData)
    {
        DB::beginTransaction();
        $model = new ProductProperty();
        $data = [];
        if ($propertyData) {
            foreach ($propertyData as $k => $v) {
                $data[$k] = [
                    'id' => $v['id'],
                    'site_id' => $productData['site_id'],
                    'product_id' => $productData['id'],
                    'name' => $v['name'],
                    'value' => $v['value'],
                    'created_at' => time()
                ];
            }
        }
        if ($productData['id']) {
            $oldData = $model::site()->select()
                ->where('product_id',$productData['id'])
                ->get();
            $oldIds = [];
            foreach ($oldData as $k => $v) {
                $oldIds[] = $v['id'];
            }
            $newIds = [];
            $insertData = [];
            $updateData = [];
            foreach ($data as $k => $v) {
                if ($v['id']) {
                    $newIds[] = $v['id'];
                    array_push($updateData,$v);
                }else{
                    array_push($insertData,$v);
                }
            }
            $model->insert($insertData);
            foreach ($updateData as $k => $v) {
                if ($v['id']) {
                    ProductProperty::where('id',$v['id'])->update(['name'=>$v['name'],'value'=>$v['value']]);
                }
            }
            $deleteIds = [];
            foreach ($oldIds as $k => $v) {
                if (!in_array($v,$newIds)) {
                    array_push($deleteIds,$v);
                }
            }
            $model::whereIn('id',$deleteIds)->delete();
        }
        if(!$model){
            DB::rollBack();
            throw new BizException('保存失败');
        }
        DB::commit();
    }

}
